<template>
  <div>
    <el-drawer v-model="drawer" :title="drawerTitle" :with-header="true" size="760px">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="140px"
        class="demo-ruleForm"
      >
        <el-form-item label="收款日期：" v-if="type === '1'" prop="collectionDate">
          <el-date-picker
            v-model="ruleForm.collectionDate"
            type="date"
            placeholder="请选择收款日期"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item label="收款金额：" v-if="type === '1'" prop="collectionAmount">
          <el-input-number
            v-model="ruleForm.collectionAmount"
            placeholder="请输入收款金额"
            style="width: 200px"
            :precision="2"
            :min="0"
          />
          &nbsp;&nbsp;元 (未分配节点金额:{{
            subtract(bignumber(ruleForm.collectionAmount), bignumber(allMount))
          }})
        </el-form-item>
        <el-form-item label="收款方式：" v-if="type === '1'">
          <el-select
            v-model="ruleForm.collectionType"
            placeholder="请选择收款方式"
            style="width: 300px"
            filterable
          >
            <el-option
              v-for="ite in approachList"
              :key="ite.id"
              :label="ite.label"
              :value="ite.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="付款日期：" v-if="type === '0'" prop="paymentDate">
          <el-date-picker
            v-model="ruleForm.paymentDate"
            type="date"
            placeholder="请选择付款日期"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item label="付款金额：" v-if="type === '0'" prop="paymentAmount">
          <el-input-number
            v-model="ruleForm.paymentAmount"
            placeholder="请输入付款金额"
            style="width: 200px"
            :precision="2"
            :min="0"
          />
          &nbsp;元 (未分配节点金额:
          {{ subtract(bignumber(ruleForm.paymentAmount), bignumber(allMount)) }})
        </el-form-item>
        <el-form-item label="付款方式：" v-if="type === '0'">
          <el-select
            v-model="ruleForm.paymentType"
            placeholder="请选择付款方式"
            style="width: 300px"
            filterable
          >
            <el-option
              v-for="ite in approachList"
              :key="ite.id"
              :label="ite.label"
              :value="ite.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input v-model="ruleForm.remark" placeholder="请输入付款备注" style="width: 300px" />
        </el-form-item>
        <el-form-item label="明细：" v-if="ruleForm.list?.length === 0">
          <el-button @click.prevent="addDomain()">
            <el-icon><Plus /></el-icon>
          </el-button>
        </el-form-item>
        <el-row v-for="(item, index) in ruleForm.list" :key="item" :gutter="20">
          <el-divider />
          <el-col :span="20">
            <el-form-item label="收/付款节点名称：">
              <el-select
                v-model="item.cycleId"
                placeholder="请选择节点"
                style="width: 300px"
                @visible-change="showSelect"
                @change="getMax"
                filterable
                clearable
              >
                <el-option
                  v-for="ite in pointList"
                  :key="ite.id"
                  :label="`${ite.pointName}后${ite.dayNumber}天`"
                  :value="ite.id"
                  :disabled="ite.disabled"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="金额"
              :prop="'list.' + index + '.amount'"
              :rules="{
                required: true,
                message: '请输入金额',
                trigger: 'blur',
              }"
            >
              <el-input-number
                v-model="item.amount"
                placeholder="请输入金额"
                style="width: 200px"
                :precision="2"
                :min="0"
                :max="item.maxAmount"
              />
              &nbsp;&nbsp;元 (该节点剩余金额:{{
                subtract(bignumber(item.maxAmount), bignumber(item.amount))
              }})
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                v-model="item.remark"
                style="width: 300px"
                :maxlength="64"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="4" style="display: flex">
            <el-button @click.prevent="addDomain()">
              <el-icon><Plus /></el-icon>
            </el-button>
            <el-button @click.prevent="removeDomain(item)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="drawer = false">取消</el-button>
          <el-button :disabled="overAmount" type="primary" @click="handleClose(ruleFormRef)"
            >确定</el-button
          >
        </span>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch, nextTick } from 'vue'
  import type { FormInstance } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { validator } from '@/utils/numberFormat.ts'
  import { getSysMoneyTypeList } from '@/api/controller/sys-user-controller/index'
  import {
    postCollectionDetail,
    putCollectionDetail,
  } from '@/api/controller/collection-detail-controller/index'
  import {
    postPaymentDetail,
    putPaymentDetail,
  } from '@/api/controller/payment-detail-controller/index'
  import { getCollectionCycleGetDetailByContractId } from '@/api/controller/collection-cycle-controller/index'
  import { getPaymentCycleGetDetailByContractId } from '@/api/controller/payment-cycle-controller/index'
  import { add, subtract, bignumber, number } from 'mathjs'
  const drawer = ref(false)
  const approachList = ref([])
  //打开弹窗
  const drawerTitle = ref()
  const ifAdd = ref(true)
  const pointList = ref([])
  const type = ref()
  const show = async (row, ty, id) => {
    type.value = ty
    getSysMoneyTypeList().then((res) => {
      approachList.value = res.data
    })
    let res
    if (ty === '1') {
      res = await getCollectionCycleGetDetailByContractId({
        contractId: id,
      })
    } else {
      res = await getPaymentCycleGetDetailByContractId({
        contractId: id,
      })
    }
    pointList.value = res.data
    overAmount.value = true
    allMount.value = 0
    if (row.id) {
      ruleForm.value = JSON.parse(JSON.stringify(row))
      drawerTitle.value = ty === '1' ? '编辑收款情况' : '编辑付款情况'
      ifAdd.value = false
    } else {
      drawerTitle.value = ty === '1' ? '新增收款情况' : '新增付款情况'
      ifAdd.value = true
      ruleForm.value = {
        contractId: id,
        collectionDate: null,
        collectionAmount: 0,
        paymentDate: null,
        paymentAmount: 0,
        collectionType: '银行转账',
        paymentType: '银行转账',
        remark: null,
        list: [],
      }
    }
    getMax()
    drawer.value = true
    nextTick(() => {
      ruleFormRef.value.clearValidate()
    })
  }

  //提交的数据
  const ruleFormRef = ref<FormInstance>()
  const ruleForm = ref({
    contractId: null,
    collectionDate: null,
    collectionAmount: 0,
    paymentDate: null,
    paymentAmount: 0,
    collectionType: null,
    paymentType: null,
    remark: null,
    list: [],
  })
  const rules = reactive({
    collectionDate: [{ required: true, message: '请选择收款日期', trigger: 'blur' }],
    collectionAmount: [
      { required: true, message: '请选择收款金额', trigger: 'blur' },
      { validator, trigger: 'blur' },
    ],
    paymentDate: [{ required: true, message: '请选择付款日期', trigger: 'blur' }],
    paymentAmount: [
      { required: true, message: '请输入付款金额', trigger: 'blur' },
      { validator, trigger: 'blur' },
    ],
    remark: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
  })

  //提交
  const handleClose = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        let result
        if (type.value === '1') {
          if (ifAdd.value) {
            result = await postCollectionDetail(ruleForm.value, { loading: true })
          } else {
            result = await putCollectionDetail(ruleForm.value, { loading: true })
          }
        } else {
          if (ifAdd.value) {
            result = await postPaymentDetail(ruleForm.value, { loading: true })
          } else {
            result = await putPaymentDetail(ruleForm.value, { loading: true })
          }
        }
        if (result.code === 200) {
          await emit('getData')
          drawer.value = false
          ElMessage.success('更新成功')
        }
      } else {
        ElMessage.warning('请正确填写表单')
        return false
      }
    })
  }

  //删除明细
  const removeDomain = (item) => {
    const index = ruleForm.value.list.indexOf(item)
    if (index !== -1) {
      ruleForm.value.list.splice(index, 1)
    }
  }

  //新增明细
  const addDomain = () => {
    ruleForm.value.list.push({
      cycleId: null,
      amount: 0,
      remark: null,
      maxAmount: 0,
    })
  }

  //确保只能选择一个节点并且节点没有完成款项
  const showSelect = () => {
    pointList.value.forEach((item) => {
      item.disabled =
        item.state === item?.collectionAmount || item.state === item?.paymentAmount ? true : false
      ruleForm.value.list.forEach((its) => {
        if (its.cycleId === item.id) {
          item.disabled = true
        }
      })
    })
  }

  //获取每个节点可分配的最大金额
  const getMax = () => {
    ruleForm.value.list.forEach((item) => {
      pointList.value.forEach((its) => {
        if (item.cycleId === its.id) {
          if (ifAdd.value) {
            if (its.collectionAmount) {
              item.maxAmount = number(
                subtract(bignumber(its.collectionAmount), bignumber(its.state)),
              )
            } else {
              item.maxAmount = number(subtract(bignumber(its.paymentAmount), bignumber(its.state)))
            }
          } else {
            if (its.collectionAmount) {
              item.maxAmount = number(
                add(
                  subtract(bignumber(its.collectionAmount), bignumber(its.state)),
                  bignumber(item.amount),
                ),
              )
            } else {
              item.maxAmount = number(
                add(
                  subtract(bignumber(its.paymentAmount), bignumber(its.state)),
                  bignumber(item.amount),
                ),
              )
            }
          }
        }
      })
    })
  }
  //监听节点总金额
  const overAmount = ref(true)
  const allMount = ref(0)
  watch(
    () => ruleForm.value,
    () => {
      allMount.value = ruleForm.value.list.reduce(
        (allAmount, item) => (allAmount = add(allAmount, item.amount)),
        0,
      )
      if (type.value === '1') {
        if (ruleForm.value.collectionAmount < allMount.value) {
          ElMessage.error('节点总金额超出收款金额！')
          overAmount.value = true
        } else if (ruleForm.value.collectionAmount === allMount.value) {
          overAmount.value = false
        } else {
          overAmount.value = true
        }
      } else {
        if (ruleForm.value.paymentAmount < allMount.value) {
          ElMessage.error('节点总金额超出付款金额！')
          overAmount.value = true
        } else if (ruleForm.value.paymentAmount === allMount.value) {
          overAmount.value = false
        } else {
          overAmount.value = true
        }
      }
    },
    { deep: true },
  )

  const emit = defineEmits(['getData'])
  defineExpose({
    show,
  })
</script>

<style lang="scss" scoped>
  .el-divider--horizontal {
    margin: 12px 0;
  }
</style>
